import 'package:flutter/widgets.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:baseProjectFlutter/widgets_common/load_switch/load_switch.dart';
import 'package:baseProjectFlutter/widgets_common/refresh/app_refresh_controller.dart';

import '../../utils/lifecycle/lifecycle.dart';
import '../../utils/other/log/log.dart';

/// 所有viewModel的父类，提供一些公共功能
abstract class BaseViewModel extends GetxController {
  BuildContext? context;
  LifecycleOwner? lifecycleOwner;
  bool _isDispose = false;
  bool _isFirst = true;

  LifecycleOwner get requireLife => lifecycleOwner!;

  //页面状态切换
  LoadStateController loadStateController = LoadStateController();

  //下拉刷新和加载更多分页
  AppRefreshController refreshController = AppRefreshController();

  BaseViewModel();

  void initState() {
    //保证只调用一次
    if (_isFirst) {
      _isFirst = false;
      onCreate();
    }
  }

  bool get isDispose => _isDispose;

  @protected
  void onCreate() {}

  void notifyListeners() {
    if (!_isDispose) {
      try {
        super.update();
      } catch (e, t) {
        LogUtils.e("BaseViewModel notifyListeners error:$e,t:$t");
      }
    }
  }

  @override
  void dispose() {
    super.dispose();
    _isDispose = true;
    lifecycleOwner = null;
  }
}
